package cn.afactory.tygz.net;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

/**
 * 用于验证签名的工具类 
 * @author YH
 *
 */
public class SignUtil {
    /**
     * 用于数据传输的token
     */
    public static final String TOKEN = "ajw2015@win";
	 /**
     * 验证是否绑定签名
     * @param signature 签名
     * @param timestamp 时间戳
     * @param openId     随机字符串
     * @return          成功否
     */
    public static boolean checkSignature(String signature, String timestamp, String openId){
        String tmpStr = createSignature(timestamp,openId);
        return tmpStr != null ? tmpStr.equals(signature.toUpperCase()): false;
    }

    public static boolean checkSignature(Sign sign){
        return checkSignature(sign.getSignature(),sign.getTimestamp(),sign.getParam());
    }
    
    public static String createSignature(Sign sign){
    	return createSignature(sign.getTimestamp(),sign.getParam());
    }
    
    public static String createSignature(String timestamp, String openId){
    	 String[] arr = new String[]{TOKEN, timestamp, openId};
         // 将 token, timestamp, openId 三个参数进行字典排序
         Arrays.sort(arr);
         StringBuilder content = new StringBuilder();
         for(int i = 0; i < arr.length; i++){
             content.append(arr[i]);
         }
         MessageDigest md = null;
         String tmpStr = null;
          
         try {
             md = MessageDigest.getInstance("SHA-1");
             // 将三个参数字符串拼接成一个字符串进行 shal 加密
             byte[] digest = md.digest(content.toString().getBytes());
             tmpStr = byteToStr(digest);
         } catch (NoSuchAlgorithmException e) {
             e.printStackTrace();
         }
         content = null;
         // 将sha1加密后的字符串可与signature对比，标识该请求来源于微信
         return tmpStr;
    }
   
    
    /**
     * 将字节数组转换为十六进制字符串
     * @param digest
     * @return
     */
    public static String byteToStr(byte[] digest) {
        String strDigest = "";
        for(int i = 0; i < digest.length; i++){
            strDigest += byteToHexStr(digest[i]);
        }
        return strDigest;
    }
    
    /**
     * 将字节转换为十六进制字符串
     * @param b
     * @return
     */
    private static String byteToHexStr(byte b) {
        char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        char[] tempArr = new char[2];
        tempArr[0] = Digit[(b >>> 4) & 0X0F];
        tempArr[1] = Digit[b & 0X0F];
         
        String s = new String(tempArr);
        return s;
    }
    
    
}
